import 'package:flutter_danmu_anim/http/user.dart';
import 'package:flutter_danmu_anim/model/model_response.dart';
import 'package:flutter_danmu_anim/model/user/info.dart';
import 'package:flutter_danmu_anim/model/user/stat.dart';
import 'package:flutter_danmu_anim/utils/storage.dart';
import 'package:get/get.dart';
import 'package:hive/hive.dart';

class MineController extends GetxController {
  // 用户信息 头像、昵称、lv
  Rx<UserInfoData> userInfo = UserInfoData().obs;

  // 用户状态 动态、关注、粉丝
  Rx<UserStat> userStat = UserStat().obs;
  Box user = GStorage.user;
  RxBool userLogin = false.obs;

  Box userInfoCache = GStorage.userInfo;

  @override
  onInit() {
    super.onInit();
    if (userInfoCache.get('userInfoCache') != null) {
      userInfo.value = userInfoCache.get('userInfoCache');
    }
  }

  onLogin() {
    if (!userLogin.value) {
      Get.toNamed(
        '/webview',
        parameters: {
          'url': 'https://passport.bilibili.com/h5-app/passport/login',
          'type': 'login',
          'pageTitle': '登录bilibili',
        },
      );
    }
  }

  Future<ResponseData<UserInfoData>> queryUserInfo() async {
    if (user.get(UserBoxKey.userLogin) == null) {
      return ResponseData(status: false);
    }
    var res = await UserHttp.userInfo();
    if (res.status) {
      if (res.data?.isLogin ?? false) {
        var data = res.data!;
        userInfo.value = data;
        userInfoCache.put('userInfoCache', data);
        user.put(UserBoxKey.userName, data.uname);
        user.put(UserBoxKey.userFace, data.face);
        user.put(UserBoxKey.userMid, data.mid);
        user.put(UserBoxKey.userLogin, true);
        userLogin.value = true;
        // Get.find<MainController>().setUserFace();
      } else {
        resetUserInfo();
      }
    } else {
      resetUserInfo();
    }
    await queryUserStatOwner();
    return res;
  }

  Future<ResponseData<UserStat>> queryUserStatOwner() async {
    var res = await UserHttp.userStatOwner();
    if (res.status) {
      userStat.value = res.data ?? UserStat();
    }
    return res;
  }

  Future resetUserInfo() async {
    userInfo.value = UserInfoData();
    userStat.value = UserStat();
    await user.delete(UserBoxKey.userName);
    await user.delete(UserBoxKey.userFace);
    await user.delete(UserBoxKey.userMid);
    await user.delete(UserBoxKey.userLogin);
    userLogin.value = false;
    // Get.find<MainController>().resetLast();
  }
}
